// 2025/5/6
// 二叉树中的最大路径和

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
    public:
        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         *
         * 
         * @param root TreeNode类 
         * @return int整型
         */
        pair<int, int> find(TreeNode* root)
        {
            // 确保second的值至少包含一个结点（当前结点）
            pair<int, int> left = root->left ? find(root->left) : pair<int, int>(0, root->val);
            pair<int, int> right = root->right ? find(root->right) : pair<int, int>(0, root->val);
            pair<int, int> cur;
            cur.first = max(0, max(left.first, right.first)) + root->val;
            int tmp1 = max(left.second, right.second);
            int tmp2 = max(cur.first, left.first + right.first + root->val);
            cur.second = max(tmp1, tmp2);
            return cur;
        }
        
        int maxPathSum(TreeNode* root) {
            // write code here
            pair<int, int> ans = find(root);
            return ans.second;
        }
    };


// 可读性更好，但前提是题目给了|maxVal| <= 1000
class Solution {
    public:
        pair<int, int> dfs(TreeNode* root)
        {
            pair<int, int> ans = {0, -1001};
            if(root == nullptr) 
                return ans;
            
            pair<int, int> left = dfs(root->left);
            pair<int, int> right = dfs(root->right);
            ans.first = max(max(left.first, right.first), 0) + root->val;
            int tmp = max(left.first + right.first + root->val, ans.first);
            ans.second = max(max(left.second, right.second), tmp);
            return ans;
        }
    
        int maxPathSum(TreeNode* root) {
            pair<int, int> ans = dfs(root);
            return ans.second;
        }
    };

